package com.fy56.platform.logistics.controller;

import com.alibaba.fastjson.JSON;
import com.fy56.platform.logistics.common.BaseController;
import com.fy56.platform.logistics.common.ResultModel;
import com.fy56.platform.logistics.model.Company;
import com.fy56.platform.logistics.model.User;
import com.fy56.platform.logistics.service.wx.ICompanyInfoService;
import com.fy56.platform.logistics.utils.ExcelUtil;
import com.fy56.platform.logistics.utils.LogUtils;
import com.fy56.platform.logistics.utils.SessionUtil;
import com.zeus.base.privilege.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;


/**
 * Created by Ning on 2018/4/28.
 */
@RestController
@RequestMapping("/controller/company")
public class CompanyController extends BaseController {
    @Autowired
    private ServletContext context;

    @Autowired
    private ICompanyInfoService iCompanyInfoService;

    /*----------------------------------------------------------------------------------------------------*/

    @RequestMapping(value = "/get", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> get(Long keyId) {
        Company c = iCompanyInfoService.getCompanyById(keyId);
        ResultModel r = ResultModel.ok(c);
        return new ResponseEntity<>(r, HttpStatus.OK);
    }

    @RequestMapping(value = "/updateCompany", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> update(Company company, HttpServletRequest request) {
        ResultModel resultModel = null;
        try {
            if (company != null) {

                //设置修改操作员，修改时间（默认当前时间）
                company.initUpdate(SessionUtil.getSessionUser(request));
                company.setUpdateUser(company.getUpdateBy().getLoginName() + "[" + company.getUpdateBy().getLoginIp() + "]");

                //执行更新操作
                resultModel = iCompanyInfoService.updateCompany(company);

                //保存系统业务日志
                LogUtils.saveLog(request, "编辑成功", company.getId().toString(), null, "CompanyManage", "update", "编辑", JSON.toJSONString(company));
                return new ResponseEntity<ResultModel>(resultModel, HttpStatus.OK);
            }
            return new ResponseEntity<ResultModel>(new ResultModel("状态编辑失败!"), HttpStatus.OK);
        } catch (Exception e) {

            //保存系统业务日志
            LogUtils.saveLog(request, "编辑失败", company.getId().toString(), null, "CompanyManage", "update", "编辑", JSON.toJSONString(company));
            return new ResponseEntity<ResultModel>(new ResultModel(EXCEPTION_MSG), HttpStatus.OK);
        } finally {
            resultModel = null;
        }
    }

    /*----------------------------------------------------------------------------------------------------*/

    @RequestMapping(value = "/selectCompanyList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<ResultModel> selectCompanyList() {
        ResultModel resultModel = null;
        List<Company> list = null;
        try {
            Company entity = null;
            list = iCompanyInfoService.selectCompanyList(entity);
        } catch (Exception e) {

        } finally {
            resultModel = null;
            return new ResponseEntity<ResultModel>(ResultModel.ok(list), HttpStatus.OK);
        }
    }

    @RequestMapping(value = "/synchroCompany", method = RequestMethod.POST)
    @ResponseBody
    public ResultModel synchroCompany(String batch, String fileUrl, Company company, HttpServletRequest request) {
        ResultModel resultModel = null;
        try {
            User user = (User)request.getSession().getAttribute("sessionUser");
            if("1".equals(batch)){
                String path = context.getRealPath("/")+"/upload/";
                if (StringUtil.isEmpty(fileUrl)) {
                    return ResultModel.error("缺少上传文件, 腾云同步-失败!");
                }
                // 从腾云服务上, 批量-同步公司信息, 根据上传文件
                resultModel = iCompanyInfoService.synchroCompanyBatch(path+fileUrl, user.getLoginName());

                ExcelUtil.fileDelete(path);
            }else{
                if (StringUtil.isEmpty(company.getCode())) {
                    return ResultModel.error("缺少总公司金融代码, 腾云同步-失败!");
                }
                if (StringUtil.isEmpty(company.getTenantPass())) {
                    return ResultModel.error("缺少总公司金融密码, 腾云同步-失败!");
                }
                // 从腾云服务上, 同步公司信息, 根据总公司信息
                resultModel = iCompanyInfoService.synchroCompany(company, user.getLoginName());
            }
            return resultModel;
        } catch (Exception e) {
            return new ResultModel(EXCEPTION_MSG);
        } finally {
            resultModel = null;
        }
    }

    /*----------------------------------------------------------------------------------------------------*/

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    @ResponseBody
    public ResultModel upload(@RequestParam(value = "xlsFile")MultipartFile xlsFile/*, HttpServletRequest request*/) throws IOException {
        ResultModel rm = ResultModel.error("上传失败");

        String path = context.getRealPath("/")+"/upload/";
        ExcelUtil.fileEstablish(path, null, null);

        String fileName = xlsFile.getOriginalFilename();
        File dir = new File(path, fileName);
        if(!dir.exists()){
            dir.mkdirs();
        }
        xlsFile.transferTo(dir);

        rm = ResultModel.ok();
        rm.setContent(fileName);
        return rm;
    }

    /*----------------------------------------------------------------------------------------------------*/

}
